#import "FlutterDeviceInfoPlugin.h"
#import <Photos/Photos.h>

@implementation FlutterDeviceInfoPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"plugins/dk_flutter_device_info"
            binaryMessenger:[registrar messenger]];
  FlutterDeviceInfoPlugin* instance = [[FlutterDeviceInfoPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getHeaderInfo" isEqualToString:call.method]) {
     NSDictionary *headerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"FlutterHeaderInfo"];
      result(headerDict);
  } else if ([@"getCacheInfo" isEqualToString:call.method]) {
      /*
       二级缓存目录(flutter相关缓存必须使用二级缓存)
       key1:dict
       dict->key2:value
       */
      NSString *firstKey = call.arguments[@"spName"];
      NSString *secondKey = call.arguments[@"spKey"];
      if (firstKey.length > 0 && secondKey.length > 0) {
          NSDictionary *param = (NSDictionary *)[[NSUserDefaults standardUserDefaults] objectForKey:firstKey];
          NSString *value = param[secondKey];
          result(value);
          return;
      }
      result(nil);
  } else if ([@"putCacheInfo" isEqualToString:call.method]) {
      NSString *firstKey = call.arguments[@"spName"];
      NSString *secondKey = call.arguments[@"spKey"];
      NSString *secondValue = call.arguments[@"spValue"];
      if (firstKey.length > 0 && secondKey.length > 0) {
          NSUserDefaults *flutterCache = [NSUserDefaults standardUserDefaults];
          NSMutableDictionary *flutterDict = [NSMutableDictionary dictionary];
          [flutterDict setValue:secondValue forKey:secondKey];
          [flutterCache setObject:flutterDict forKey:firstKey];
          result(@YES);
          return;
      }
      result(nil);
  } else if ([@"refreshAlbum" isEqualToString:call.method]) {
      NSString *imagePath = call.arguments[@"imageAbsolutePath"];
            BOOL isInsert = (BOOL)call.arguments[@"isInsertAlbum"];
            if (isInsert) {
                //相册权限
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    if (status == PHAuthorizationStatusNotDetermined || status == PHAuthorizationStatusAuthorized) {
                        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
                        result(@YES);
                    } else {
                        [self showSettingAlertStr:@"请在“设置->隐私->照片”中打开本应用的“读取和写入”权限"];
                        result(@NO);
                    }
                }];
            }
  } else {
    result(FlutterMethodNotImplemented);
  }
}

- (void)showSettingAlertStr:(NSString *)tipStr {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您还未开启相册权限" message:tipStr preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }]];
    [[self currentViewController] presentViewController:alert animated:YES completion:nil];
}


- (UIViewController *)currentViewController {
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    //获取根控制器
    UIViewController* currentViewController = window.rootViewController;
    //获取当前页面控制器
    BOOL runLoopFind = YES;
    while (runLoopFind){
        if (currentViewController.presentedViewController){
            currentViewController = currentViewController.presentedViewController;
        }else if ([currentViewController isKindOfClass:[UINavigationController class]]){
            UINavigationController* navigationController = (UINavigationController* )currentViewController;
            currentViewController = [navigationController.childViewControllers lastObject];
        } else if ([currentViewController isKindOfClass:[UITabBarController class]]){
            UITabBarController* tabBarController = (UITabBarController* )currentViewController;
            currentViewController = tabBarController.selectedViewController;
        } else {
            NSUInteger childViewControllerCount = currentViewController.childViewControllers.count;
            if (childViewControllerCount > 0) {
                currentViewController = currentViewController.childViewControllers.lastObject;
                return currentViewController;
            } else {
                return currentViewController;
            }
        }
    }
    return currentViewController;
}

@end
